import localCache from '@/utils/cache'
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'

const routers: RouteRecordRaw[] = [
  {
    path: '/',
    redirect: '/main'
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/main',
    name: 'main',
    children: [],
    component: () => import('@/views/main/main.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: () => import('@/views/notfound/not-found.vue')
  }
]

const router = createRouter({
  routes: routers,
  history: createWebHistory()
})

router.beforeEach((to) => {
  if (to.path !== '/login') {
    const token = localCache.getToken()
    if (!token) {
      return '/login'
    }
  }
  if (to.path === '/main') {
    const fistMenu = localCache.getFirstMenu()
    if (fistMenu) {
      return fistMenu.url
    }
  }
})
export default router
